﻿using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinForm_Mes.WorkingManagement.TeamType
{
    public partial class TeamTypeForm : DevExpress.XtraEditors.XtraForm
    {
        private HttpClient httpClient;
        private string baseUrl = "http://localhost:5053"; // 替换为实际的API基础URL
        private int pageIndex = 1;
        private int pageSize = 10;
        private int pageCount = 0;
        public TeamTypeForm()
        {
            InitializeComponent();
            InitializeHttpClient();
            InitializeGridControl();
        }

        private void InitializeHttpClient()
        {
            httpClient = new HttpClient();
            httpClient.BaseAddress = new Uri(baseUrl);
            httpClient.DefaultRequestHeaders.Accept.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
        }

        private void InitializeGridControl()
        {
            // 设置GridView多选模式
            gridView1.OptionsSelection.MultiSelect = true;
            gridView1.OptionsSelection.MultiSelectMode = GridMultiSelectMode.CheckBoxRowSelect;
            
            
        }
        private async void TeamTypeForm_Load_1(object sender, EventArgs e)
        {
            await LoadTeamTypeData();
        }

        private async void btnQuery_Click(object sender, EventArgs e)
        {
            pageIndex = 1;
            await LoadTeamTypeData();
        }

        private async Task LoadTeamTypeData()
        {
            try
            {
                // 构建查询参数
                string teamTypeName = textEdit1.Text.Trim();
                string createUser = textEdit2.Text.Trim();
                string createTimes =dateEdit1.EditValue != null ? Convert.ToDateTime(dateEdit1.EditValue).ToString("yyyy-MM-dd") : "";
               
                string url = $"/api/Scheduling/GetTeamTypeList?TeamTypeName={teamTypeName}&CreateUser={createUser}&CreateTime={createTimes}&PageIndex={pageIndex}&PageSize={pageSize}";

                HttpResponseMessage response = await httpClient.GetAsync(url);
                if (response.IsSuccessStatusCode)
                {
                    string responseData = await response.Content.ReadAsStringAsync();
                    var result = JsonConvert.DeserializeObject<TeamTypeResponse>(responseData);
                    result.items.ForEach(item =>
                    {
                        item.createTime = Convert.ToDateTime(item.createTime).ToString("yyyy-MM-dd HH:mm:ss");
                    });
                    pageCount = (int)Math.Ceiling((double)result.total/pageSize);
                    if (result.code == 200)
                    {
                        gridControl1.DataSource = result.items;
                        textEdit3.Text = pageIndex.ToString();
                        
                        labelControl4.Text = $"共 {result.total} 条记录,当前第{pageIndex}/{pageCount}页";
                    }
                    else
                    {
                        XtraMessageBox.Show($"查询失败：{result.message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    XtraMessageBox.Show($"请求失败：{response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"发生异常：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async void btnPrev_Click(object sender, EventArgs e)
        {
            if (pageIndex > 1)
            {
                pageIndex--;
                await LoadTeamTypeData();
            }
        }

        private async void btnNext_Click(object sender, EventArgs e)
        {
            if (pageIndex<pageCount)
            {
                pageIndex++;
                await LoadTeamTypeData();
            }
            
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            AddTeamTypeForm addForm = new AddTeamTypeForm();
            if (addForm.ShowDialog() == DialogResult.OK)
            {
                LoadTeamTypeData();
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (gridView1.GetSelectedRows().Length == 0)
            {
                XtraMessageBox.Show("请选择要编辑的记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            int rowHandle = gridView1.GetSelectedRows()[0];
            if (rowHandle >= 0)
            {
                var selectedItem = gridView1.GetRow(rowHandle) as TeamTypeItem;
                UpdateTeamTypeForm updateForm = new UpdateTeamTypeForm(selectedItem);
                if (updateForm.ShowDialog() == DialogResult.OK)
                {
                    LoadTeamTypeData();
                }
            }
        }

        // 删除按钮点击事件
        private async void btnDelete_Click(object sender, EventArgs e)
        {
            // 获取所有选中行
            int[] selectedRows = gridView1.GetSelectedRows();
            if (selectedRows.Length == 0)
            {
                XtraMessageBox.Show("请选择要删除的记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // 确认是否删除
            if (XtraMessageBox.Show($"确定要删除选中的 {selectedRows.Length} 条记录吗？", "确认删除", 
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
            {
                return;
            }

            // 收集所有选中记录的ID
            List<long> idsToDelete = new List<long>();
            foreach (int rowHandle in selectedRows)
            {
                if (rowHandle >= 0)
                {
                    var selectedItem = gridView1.GetRow(rowHandle) as TeamTypeItem;
                    if (selectedItem != null)
                    {
                        idsToDelete.Add(selectedItem.id);
                    }
                }
            }

            // 删除所有选中记录
            bool hasError = false;
            foreach (long id in idsToDelete)
            {
                bool success = await DeleteTeamType(id);
                if (!success)
                {
                    hasError = true;
                }
            }

            // 刷新数据
            await LoadTeamTypeData();

            // 显示操作结果
            if (hasError)
            {
                XtraMessageBox.Show("部分记录删除失败，请查看详细错误信息", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                XtraMessageBox.Show("删除成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        // 删除团队类型方法
        private async Task<bool> DeleteTeamType(long id)
        {
            try
            {
                // 构建删除API的URL，不再在URL中传递参数
                string url = $"/api/Scheduling/DeleteTeamType";

                // 创建请求内容，将ID放入请求体中
                var content = new StringContent(
                    JsonConvert.SerializeObject(new { id = id }),
                    Encoding.UTF8,
                    "application/json");

                // 发送POST请求
                HttpResponseMessage response = await httpClient.PostAsync(url, content);
                
                // 处理响应
                if (response.IsSuccessStatusCode)
                {
                    string responseData = await response.Content.ReadAsStringAsync();
                    var result = JsonConvert.DeserializeObject<BaseResponse>(responseData);
                    
                    if (result.code == 200)
                    {
                        return true;
                    }
                    else
                    {
                        XtraMessageBox.Show($"删除ID为{id}的记录失败：{result.message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return false;
                    }
                }
                else
                {
                    XtraMessageBox.Show($"删除ID为{id}的记录请求失败：{response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"删除ID为{id}的记录时发生异常：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            pageIndex = 1;
            LoadTeamTypeData();
        }

        private void simpleButton9_Click(object sender, EventArgs e)
        {
            LoadTeamTypeData();
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            textEdit1.Text = "";
            textEdit2.Text = "";
            dateEdit1.EditValue = null;
        }

        private async void textEdit3_Leave(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textEdit3.Text))
            {
                textEdit3.Text = pageIndex.ToString();
                return;
            }

            if (!int.TryParse(textEdit3.Text, out int targetPage))
            {
                XtraMessageBox.Show("请输入有效的页码", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                textEdit3.Text = pageIndex.ToString();
                return;
            }

            // 页码范围验证
            if (targetPage < 1)
            {
                XtraMessageBox.Show("页码不能小于1", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                textEdit3.Text = pageIndex.ToString();
                return;
            }

            if (targetPage > pageCount)
            {
                XtraMessageBox.Show($"页码不能大于总页数 {pageCount}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                textEdit3.Text = pageIndex.ToString();
                return;
            }

            // 如果输入的页码与当前页码不同，则跳转
            if (targetPage != pageIndex)
            {
                pageIndex = targetPage;
                await LoadTeamTypeData();
            }
        }

        private void textEdit3_EditValueChanged(object sender, EventArgs e)
        {

        }

        private void gridControl1_Click(object sender, EventArgs e)
        {

        }
    }

    // 响应数据模型
    public class TeamTypeResponse
    {
        public int total { get; set; }
        public int pageIndex { get; set; }
        public int pageSize { get; set; }
        public List<TeamTypeItem> items { get; set; }
        public int code { get; set; }
        public string message { get; set; }
        public object data { get; set; }
    }

    public class TeamTypeItem
    {
        public long id { get; set; }
        public string teamTypeCode { get; set; }
        public string teamTypeName { get; set; }
        public string createUser { get; set; }
        public string createTime { get; set; }
        public string remark { get; set; }
    }

    

    // 基础响应模型
    public class BaseResponse
    {
        public int code { get; set; }
        public string message { get; set; }
        public object data { get; set; }
    }
}